const express = require('express')
const common = require('../../libs/common')
const mysql = require('mysql')
const db = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: '123456789',
  database: 'learner'
})

module.exports = function () {
  let router = express.Router()

  router.get('/', (req, res) => {
    res.render('admin/login.ejs', {})
  })

  router.post('/', (req, res) => {
    let username = req.body.username
    let password = common.md5(req.body.password + common.MD5_SUFFIX)
    db.query(`SELECT * FROM admin_table WHERE username='${username}'`, (err, data) => {
      if (err) {
        console.log(err)
        res.status(500).send('database error').end()
      } else {
        if (data.length) {
          if (data[0].password === password) {
            // 登陆校验通过
            req.session['admin_id'] = data[0].id  // 注入session
            res.redirect('/admin/')
          } else {
            res.status(404).send('this password is incorrect.').end()
          }
        } else {
          res.status(400).send('no this admin').end()
        }
      }
    })
  })

  return router
}
